import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { AppModule } from './app.module';
import { setupSwagger } from './config/swagger.config';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
import { AllExceptionFilter } from './common/filters/all-exception.filter';
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
import { LoggerService } from './common/logger/logger.service';

async function bootstrap() {
  // 创建应用实例，使用自定义 Logger
  const app = await NestFactory.create(AppModule, {
    logger: new LoggerService(),
  });

  // 全局前缀
  app.setGlobalPrefix(process.env.API_PREFIX || 'api');

  // ==================== 全局验证管道 ====================
  app.useGlobalPipes(
    new ValidationPipe({
      // 自动转换类型
      transform: true,
      // 去除未定义的属性
      whitelist: true,
      // 禁止未定义的属性
      forbidNonWhitelisted: true,
      // 启用隐式类型转换
      transformOptions: {
        enableImplicitConversion: true,
      },
    }),
  );

  // ==================== 全局过滤器 ====================
  // 注意：顺序很重要！先注册全局异常过滤器，再注册 HTTP 异常过滤器
  app.useGlobalFilters(new AllExceptionFilter(), new HttpExceptionFilter());

  // ==================== 全局拦截器 ====================
  app.useGlobalInterceptors(new TransformInterceptor());

  // ==================== CORS 配置 ====================
  app.enableCors({
    origin: process.env.FRONTEND_URL || 'http://localhost:3000',
    credentials: true,
  });

  // ==================== Swagger 配置 ====================
  if (process.env.NODE_ENV !== 'production') {
    setupSwagger(app);
  }

  const port = process.env.PORT || 3001;
  await app.listen(port);

  const logger = new LoggerService();
  logger.log(`🚀 Application is running on: http://localhost:${port}`);
  logger.log(`📚 API Prefix: ${process.env.API_PREFIX || 'api'}`);
  if (process.env.NODE_ENV !== 'production') {
    logger.log(`📖 Swagger Docs: http://localhost:${port}/api/docs`);
  }
}

bootstrap();
